package com.helen.mybatis.session;

import com.helen.mybatis.configration.Configuration;
import com.helen.mybatis.configration.MappedStatement;
import com.helen.mybatis.executor.SimpleExecutor;
import com.helen.mybatis.proxy.ProxyMapper;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.sql.SQLException;
import java.util.List;

/**
 * @author helenlee
 * @date 2020/4/8
 */
public class DefaultSqlSessionImpl implements SqlSession {
    private Configuration configuration;

    private SimpleExecutor simpleExecutor = new SimpleExecutor();


    public DefaultSqlSessionImpl(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <T> T getMapper(Class clazz) {
        ProxyMapper proxyMapper = new ProxyMapper(this);
        return (T) Proxy.newProxyInstance(DefaultSqlSessionImpl.class.getClassLoader(), new Class[]{clazz}, proxyMapper);
    }

    @Override
    public Configuration getConfiguration() {
        return this.configuration;
    }

    @Override
    public <T> T selectOne(String statementId, Object... param) {
        return (T) this.selectList(statementId, param).get(0);
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... param) {
        MappedStatement mappedStatement = configuration.getMappedStatementById(statementId);
        List<E> result = null;
        try {
            result = simpleExecutor.query(mappedStatement, param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    @Override
    public int update(String statementId, Object... param) {
        MappedStatement mappedStatement = configuration.getMappedStatementById(statementId);
        int update = 0;
        try {
            update = simpleExecutor.update(mappedStatement, param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return update;
    }
}
